/******************************************************************************************************
Copyright (C) 2017 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals BaseConverter, NMRSpectrum, print, File, Str, TextStream, Env, Application*/
/*jslint plusplus: true, indent: 4*/

/** Default constructor of the converter
 * Defines the file filter
*/
function IntegralTableConverter() {
	"use strict";
	BaseConverter.call(this);
	this.exportFileFilter = "Integral Table (*.txt)"; //!< It will override any other script converter with the same exportFileFilter
}
IntegralTableConverter.prototype = new BaseConverter();

/** Can export integrals of 1D and 2D NMRSpectra
 */
IntegralTableConverter.prototype.wantsExport = function (aPageItems) {
	"use strict";
	var i, nmrSpc;

	for (i = 0; i < aPageItems.length; i++) {
		if (aPageItems[i].name === "NMR Spectrum") {
			nmrSpc = new NMRSpectrum(aPageItems[i]);
			if (nmrSpc.isValid()) {
				if ((nmrSpc.dimCount === 1 ||  nmrSpc.dimCount === 2) && nmrSpc.integrals().count !== 0) {
					return true;
				}
			}
		}
	}
	return false;
};

/** Writes the file
 */
IntegralTableConverter.prototype.exportItems = function (aPageItems, aFilename) {
	"use strict";

	print(aPageItems);
	print(aFilename);

	var resultsTable, i, nmrSpc, originalSpcIndex, spcCount, s, integralList, integralResult, j,
		integral, F1From, F1To, absValue, normValue, F2From, F2To, output, strm,
		specCounter = 0,
		precision = 5,
		file = new File(aFilename);

	if (file.open(File.WriteOnly)) {
	    resultsTable = [];

	    for (i = 0; i < aPageItems.length; i++) {
			if (aPageItems[i].name === "NMR Spectrum") {
				specCounter++;
				nmrSpc = new NMRSpectrum(aPageItems[i]);
				originalSpcIndex = nmrSpc.curSpecIndex;
				spcCount = nmrSpc.specCount;
				for (s = 0; s < spcCount; s++) { //it could be an arrayed spectrum
					nmrSpc.curSpecIndex = s;
					integralList = nmrSpc.integrals();
					integralResult = {};
					if (Str.toOneWord(nmrSpc.title)) { //toOneWord defined in string.qs
						integralResult.title = '"' + Str.toOneWord(nmrSpc.title) + '"\n';
					} else {
						integralResult.title = "\n";
					}
					integralResult.table = "";
					if (integralList.count) {
						for (j = 0; j < integralList.count; j++) {
							integral = integralList.at(j);
							F1From = integral.rangeMin(1);
							F1To = integral.rangeMax(1);
							absValue = integral.integralValue(1.0);
							normValue = integral.integralValue(integralList.normValue);
							if (nmrSpc.dimCount === 1) {
								integralResult.table += "{0}\t{1}\t{2}\t{3}\n".replace('{0}', F1From.toFixed(precision)).replace('{1}', F1To.toFixed(precision)).replace('{2}', normValue.toFixed(precision)).replace('{3}', absValue.toFixed(precision));
							} else if (nmrSpc.dimCount === 2) {
								F2From = integral.rangeMin(2);
								F2To = integral.rangeMax(2);
								integralResult.table += "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\n".replace('{0}', F2From.toFixed(precision)).replace('{1}', F2To.toFixed(precision)).replace('{2}', F1From.toFixed(precision)).replace('{3}', F1To.toFixed(precision)).replace('{4}', normValue.toFixed(precision)).replace('{5}', absValue.toFixed(precision));
							}
						}
					}
					resultsTable.push(integralResult);
				}
			}
	    }
	    output = "";
	    for (i = 0; i < resultsTable.length; i++) {
			if (resultsTable.length > 1) {
				output += resultsTable[i].title;
			}
			output += resultsTable[i].table;
	    }

	    strm = new TextStream(file);
	    strm.write(output);
	    nmrSpc.curSpecIndex = originalSpcIndex;
	    file.close();
	    return 0;
	}
	return 1;
};

/** Add to the Env.Converters environment engine
 */
Env.Converters.push(new IntegralTableConverter());

//test
function IntegralTableConverterTest() {
	"use strict";
	var retVal = -1,
		integralTableConv = new IntegralTableConverter(),
		pageItems = Application.mainWindow.activeDocument.selection();

	if (integralTableConv.wantsExport(pageItems)) {
		retVal = integralTableConv.exportItems(pageItems, "C:/integrals.txt");
	}
	return retVal;
}
